#!/bin/bash
INSTALLDIR=$(cd "$(dirname "$0")"; pwd);
CHECK_NUMBER_SCRIPT=$INSTALLDIR/checknumber.sh
KILL_PORT_SCRIPT=$INSTALLDIR/killport.sh
LOCAL_PORT=
ERROR=1
CHECK_SUCCESS=1

input_local_port () {

    PORT_SUCCESS=1;
    while true
    do 
        printf "Enter tunnel remote port:" $LOCAL_PORT;
        read LOCAL_PORT
		if [ ! $LOCAL_PORT ] ; then
			echo 'Please enter a port number';
		else
			if test -x $CHECK_NUMVER_SCRIPT; then
				$CHECK_NUMBER_SCRIPT $LOCAL_PORT
				if [ $? -eq 0 ]; then
					CHECK_SUCCESS=0; 
					PORT_SUCCESS=0;
					break;    
				fi
			fi
		fi
    done 
    return $PORT_SUCCESS
	
}

stop_ssh_tunnel () {
    if [ $CHECK_SUCCESS -eq 0 ]; then
		if test -x $KILL_PORT_SCRIPT; then
            $KILL_PORT_SCRIPT $LOCAL_PORT
            if [ $? -eq 0 ]; then
				ERROR=0;
			else
				ERROR=1;
            fi
		fi    
    fi
}
input_local_port && stop_ssh_tunnel

exit $ERROR

